package com.jy.horny.function.register

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Matrix
import android.os.Build
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.jy.horny.R
import com.jy.horny.ToastUtil
import com.jy.horny.adapter.RegisterDateAdapter
import com.jy.horny.adapter.RegisterPhotoAdapter
import com.jy.horny.base.BaseVMActivity
import com.jy.horny.databinding.ActivityRegisterBinding
import com.jy.horny.dialog.UploadPhotoDialog
import com.jy.horny.function.MainActivity
import com.jy.horny.model.PhotoModel
import com.jy.horny.utils.OpenAlbumCameraUtil
import com.jy.horny.utils.upload.UploadFileUtil
import com.lib.module_base.utils.getCurrentYear
import com.lib.module_base.utils.isUnderEighteen
import com.lib.module_base.utils.isValidDate
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date


/**
 * 注册页面
 */
class RegisterActivity : BaseVMActivity<ActivityRegisterBinding, RegisterViewModel>(
    ActivityRegisterBinding::inflate,
    RegisterViewModel::class.java
) {
    private var adapterPhoto: RegisterPhotoAdapter? = null
    private var photoSelectIndex: Int = 0
    private var imgList = arrayListOf(
        PhotoModel("", "", false),
        PhotoModel("", "", false),
        PhotoModel("", "", false),
        PhotoModel("", "", false),
        PhotoModel("", "", false),
        PhotoModel("", "", false)
    )

    private var currentPage = 0

    //顶部
    private var currentTranslationX = 0f
    private val segmentWidth by lazy { binding.imgRegisterTop.drawable.intrinsicWidth / 3.2f } // 将图片分为三段
    private val maxTranslationX by lazy { binding.imgRegisterTop.drawable.intrinsicWidth - binding.imgRegisterTop.width.toFloat() } // 最大平移距离

    //中间
    private var middleCurrentTranslationX = 0f
    private val middleSegmentWidth by lazy { binding.imgRegisterMiddle.drawable.intrinsicWidth / 3.2f } // 将图片分为三段
    private val middleMaxTranslationX by lazy { binding.imgRegisterMiddle.drawable.intrinsicWidth - binding.imgRegisterMiddle.width.toFloat() } // 最大平移距离

    //底部
    private var bottomCurrentTranslationX = 0f
    private val bottomSegmentWidth by lazy { binding.imgRegisterBottom.drawable.intrinsicWidth / 3.2f } // 将图片分为三段
    private val bottomMaxTranslationX by lazy { binding.imgRegisterBottom.drawable.intrinsicWidth - binding.imgRegisterBottom.width.toFloat() } // 最大平移距离
    private val monthList by lazy { resources.getStringArray(R.array.month_array).toMutableList() }
    private val dayList by lazy { resources.getStringArray(R.array.day_array).toMutableList() }
    private val yearList by lazy { (1930..getCurrentYear().toInt()).toList().map { it.toString() } }
    private val adapter by lazy { RegisterDateAdapter() }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initData() {
        binding.imgRegisterTop.post {
            // 初始top位置：显示图片的最右边
            currentTranslationX = -maxTranslationX
            setTranslationXTop(currentTranslationX)
        }
        binding.imgRegisterMiddle.post {
            // 初始middle位置：显示图片的最左边
            middleCurrentTranslationX = 0f
            setTranslationXMiddle(middleCurrentTranslationX)
        }
        binding.imgRegisterBottom.post {
            // 初始bottom位置：显示图片的最左边
            bottomCurrentTranslationX = 0f
            setTranslationXBottom(bottomCurrentTranslationX)
        }
        binding.vRegisterOneMonth.setOnClickListener {
            //点击月份
            binding.rvRegisterOneMonth.visibility = View.VISIBLE
            binding.rvRegisterOneDay.visibility = View.INVISIBLE
            binding.rvRegisterOneYear.visibility = View.INVISIBLE
            binding.imgRegisterMonthExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_up)
            binding.imgRegisterDayExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
            binding.imgRegisterYearExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
            binding.rvRegisterOneMonth.layoutManager = LinearLayoutManager(this)
            adapter.set(monthList, 0)
            binding.rvRegisterOneMonth.adapter = adapter
        }
        binding.vRegisterOneDay.setOnClickListener {
            //点击日
            binding.rvRegisterOneMonth.visibility = View.INVISIBLE
            binding.rvRegisterOneDay.visibility = View.VISIBLE
            binding.rvRegisterOneYear.visibility = View.INVISIBLE
            binding.imgRegisterMonthExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
            binding.imgRegisterDayExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_up)
            binding.imgRegisterYearExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
            binding.rvRegisterOneDay.layoutManager = LinearLayoutManager(this)
            adapter.set(dayList, 1)
            binding.rvRegisterOneDay.adapter = adapter
        }
        binding.vRegisterOneYear.setOnClickListener {
            //点击年
            binding.rvRegisterOneMonth.visibility = View.INVISIBLE
            binding.rvRegisterOneDay.visibility = View.INVISIBLE
            binding.rvRegisterOneYear.visibility = View.VISIBLE
            binding.imgRegisterMonthExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
            binding.imgRegisterDayExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
            binding.imgRegisterYearExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_up)
            binding.rvRegisterOneYear.layoutManager = LinearLayoutManager(this)
            adapter.set(yearList, 2)
            binding.rvRegisterOneYear.adapter = adapter
        }
        //点击年月日的item事件
        adapter.setOnItemClickListener(object : RegisterDateAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, type: Int) {
                binding.rvRegisterOneMonth.visibility = View.INVISIBLE
                binding.rvRegisterOneDay.visibility = View.INVISIBLE
                binding.rvRegisterOneYear.visibility = View.INVISIBLE
                when (type) {
                    0 -> {
                        //月
                        binding.imgRegisterMonthExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
                        binding.txtRegisterMonthOne.text = monthList[position]
                    }

                    1 -> {
                        //日
                        binding.imgRegisterDayExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
                        binding.txtRegisterDayOne.text = dayList[position]
                    }

                    2 -> {
                        //年
                        binding.imgRegisterYearExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
                        binding.txtRegisterYearOne.text = yearList[position]
                    }
                }

            }
        })
        //点击第一个下一步按钮
        binding.conRegisterBtnOne.setOnClickListener {
            //先拿到月的索引
            val indexMonth = monthList.indexOf(binding.txtRegisterMonthOne.text.toString())
            //再索引前追加一个0
            val month = if (indexMonth <= 8) "0${indexMonth + 1}" else (indexMonth + 1).toString()
            val dateString =
                "${binding.txtRegisterYearOne.text}-${month}-${binding.txtRegisterDayOne.text}"
            if (isValidDate(dateString)) {
                if (isUnderEighteen(dateString)) {
                    ToastUtil.showToast("Age is less than 18 years")
                } else {
                    ToastUtil.showToast("Age is 18 years or older")
                    binding.rvRegisterOneMonth.visibility = View.INVISIBLE
                    binding.rvRegisterOneDay.visibility = View.INVISIBLE
                    binding.rvRegisterOneYear.visibility = View.INVISIBLE
                    binding.imgRegisterMonthExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
                    binding.imgRegisterDayExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
                    binding.imgRegisterYearExpand.setImageResource(com.lib.module_res.R.mipmap.img_register_down)
                    shiftImageTop(false)
                    shiftImageMiddle(false)
                    shiftImageBottom(false)
                    shiftPage(false)
                }
            } else {
                ToastUtil.showToast("Invalid date format")
            }
        }
        //点击第二个下一步按钮
        binding.conRegisterBtnTwo.setOnClickListener {
            shiftImageTop(false)
            shiftImageMiddle(false)
            shiftImageBottom(false)
            shiftPage(false)
        }
        //点击第三个下一步按钮
        binding.txtRegisterNextThree.setOnClickListener {
            //跳转首页
            MainActivity.start(this)
        }
        //点击跳过
        binding.txtRegisterSkipThree.setOnClickListener {
            //跳转首页
            MainActivity.start(this)
        }
        //点击返回键
        binding.imgRegisterBack.setOnClickListener {
            binding.rvRegisterOneMonth.visibility = View.INVISIBLE
            binding.rvRegisterOneDay.visibility = View.INVISIBLE
            binding.rvRegisterOneYear.visibility = View.INVISIBLE
            //1、当在一个页面，顶部没有返回键，但是点击底部物理按键的返回 回到登录页面；
            //2、第二、三个页面，有返回键，点击底部返回和顶部返回，此时动画回到上一个步骤
            shiftImageTop(true)
            shiftImageMiddle(true)
            shiftImageBottom(true)
            shiftPage(true)
        }
        showDate()
        initPhoto()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initPhoto() {
        binding.rvRegisterThreePhoto.layoutManager = GridLayoutManager(this, 3)
        adapterPhoto = RegisterPhotoAdapter(object : RegisterPhotoAdapter.OnItemPhotoClickListener {
            override fun selectItemPhoto(url: String, position: Int) {
                photoSelectIndex = position
                UploadPhotoDialog.Builder(this@RegisterActivity)
                    .setCallback(object : UploadPhotoDialog.Callback {
                        override fun onBackClick(type: Int?) {
                            if (type == 1) {
                                OpenAlbumCameraUtil.openAlbum(this@RegisterActivity)
                            } else {
                                OpenAlbumCameraUtil.openCamera(this@RegisterActivity)
                            }
                        }
                    }).show()
            }

            override fun deleteItemPhoto(url: String, position: Int) {
                imgList.removeAt(position)
                imgList.add(PhotoModel("", "", false))
                binding.txtRegisterNextThree.isEnabled = imgList[0].imgUrl != ""
                adapterPhoto?.getDataList()?.clear()
                adapterPhoto?.getDataList()?.addAll(imgList)
                adapterPhoto?.notifyDataSetChanged()
            }

        })
        adapterPhoto?.getDataList()?.addAll(imgList)
        binding.rvRegisterThreePhoto.adapter = adapterPhoto
        adapterPhoto?.notifyDataSetChanged()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    val selectList = PictureSelector.obtainSelectorList(data)
                    addImage(selectList)
                }
            }
        }
    }

    private fun addImage(selectList: ArrayList<LocalMedia>?) {
        selectList?.forEach {
            val path = when {
                it.isCompressed -> {
                    it.compressPath
                }

                it.isCut -> {
                    it.cutPath
                }

                else -> {
                    it.realPath
                }
            }
            if (path.contains(".mp4", true) || it.mimeType.contains(
                    ".3gp",
                    true
                ) || it.mimeType.contains(".mov", true)
            ) {
                ToastUtil.showToast("pls upload photo.")
                return
            }

            if (imgList[photoSelectIndex].imgUrl != "") {
                imgList[photoSelectIndex].imgUrl = ""
                imgList[photoSelectIndex].state = true
                adapterPhoto?.notifyItemChanged(photoSelectIndex)
            } else {
                for (i in 0 until imgList.size) {
                    if (imgList[i].imgHttpUrl == "" && !imgList[i].state) {
                        imgList[i].state = true
                        adapterPhoto?.notifyItemChanged(i)
                        break
                    }

                }
            }
            UploadFileUtil.uploadFileNew(
                this,
                path,
                it.mimeType,
                object : UploadFileUtil.OnLister {
                    override fun onSuccess(successPath: String, imageCode: String) {
                        var showPosition = 0
                        for (i in 0 until imgList.size) {
                            if (imgList[i].imgUrl == "") {
                                showPosition = i
                                break
                            }
                        }
                        imgList[showPosition].imgUrl = path
                        imgList[showPosition].imgHttpUrl = successPath
                        imgList[showPosition].state = false
                        adapterPhoto?.notifyItemChanged(showPosition)
                        binding.txtRegisterNextThree.isEnabled = true
                    }

                    override fun fail() {
                        ToastUtil.showToast("upload error,pls try again")
                    }

                })
        }
    }

    //初始化显示日期
    @SuppressLint("SimpleDateFormat")
    private fun showDate() {
        //根据当前日期计算出十八岁的出生日期
        val calendar: Calendar = Calendar.getInstance()
        calendar.add(Calendar.YEAR, -18)
        val eighteenYearsAgo: Date = calendar.time
        val sdf = SimpleDateFormat("yyyy-MM-dd")
        val formattedDate: String = sdf.format(eighteenYearsAgo)
        // 截取年份
        val year = formattedDate.substring(0, 4)
        binding.txtRegisterYearOne.text = year
        // 截取月份
        val month = formattedDate.substring(5, 7)
        month.toInt()
        binding.txtRegisterMonthOne.text = monthList[month.toInt() - 1]
        // 截取日期
        val day = formattedDate.substring(8, 10)
        binding.txtRegisterDayOne.text = day
    }

    //底部图片动画
    private fun setTranslationXBottom(translationX: Float) {
        val matrix = Matrix()
        matrix.postTranslate(translationX, 0f)
        binding.imgRegisterBottom.imageMatrix = matrix
    }

    private fun shiftImageBottom(isBack: Boolean) {
        val newTranslationX =
            if (isBack) bottomCurrentTranslationX + bottomSegmentWidth else bottomCurrentTranslationX - bottomSegmentWidth
        if (newTranslationX >= -bottomMaxTranslationX) {
            ObjectAnimator.ofFloat(bottomCurrentTranslationX, newTranslationX).apply {
                duration = 500 // 动画时长
                addUpdateListener { animation ->
                    val value = animation.animatedValue as Float
                    setTranslationXBottom(value)
                }
                start()
            }
            bottomCurrentTranslationX = newTranslationX
        } else {
            // 如果到达右边界，重置到最左边
            ObjectAnimator.ofFloat(bottomCurrentTranslationX, 0f).apply {
                duration = 500 // 动画时长
                addUpdateListener { animation ->
                    val value = animation.animatedValue as Float
                    setTranslationXBottom(value)
                }
                start()
            }
            bottomCurrentTranslationX = 0f
        }
    }

    //中间图片动画
    private fun setTranslationXMiddle(translationX: Float) {
        val matrix = Matrix()
        matrix.postTranslate(translationX, 0f)
        binding.imgRegisterMiddle.imageMatrix = matrix
    }

    private fun shiftImageMiddle(isBack: Boolean) {
        val newTranslationX =
            if (isBack) middleCurrentTranslationX + middleSegmentWidth else middleCurrentTranslationX - middleSegmentWidth
        if (newTranslationX >= -middleMaxTranslationX) {
            ObjectAnimator.ofFloat(middleCurrentTranslationX, newTranslationX).apply {
                duration = 500 // 动画时长
                addUpdateListener { animation ->
                    val value = animation.animatedValue as Float
                    setTranslationXMiddle(value)
                }
                start()
            }
            middleCurrentTranslationX = newTranslationX
        } else {
            // 如果到达右边界，重置到最左边
            ObjectAnimator.ofFloat(middleCurrentTranslationX, 0f).apply {
                duration = 500 // 动画时长
                addUpdateListener { animation ->
                    val value = animation.animatedValue as Float
                    setTranslationXMiddle(value)
                }
                start()
            }
            middleCurrentTranslationX = 0f
        }
    }

    //顶部图片动画
    private fun setTranslationXTop(translationX: Float) {
        val matrix = Matrix()
        matrix.postTranslate(translationX, 0f)
        binding.imgRegisterTop.imageMatrix = matrix
    }

    private fun shiftImageTop(isBack: Boolean) {
        val newTranslationX =
            if (isBack) currentTranslationX - segmentWidth else currentTranslationX + segmentWidth
        if (newTranslationX <= 0) {
            ObjectAnimator.ofFloat(currentTranslationX, newTranslationX).apply {
                duration = 500 // 动画时长
                addUpdateListener { animation ->
                    val value = animation.animatedValue as Float
                    setTranslationXTop(value)
                }
                start()
            }
            currentTranslationX = newTranslationX
        } else {
            // 如果到达左边界，重置到右边
            ObjectAnimator.ofFloat(currentTranslationX, -maxTranslationX).apply {
                duration = 500 // 动画时长
                addUpdateListener { animation ->
                    val value = animation.animatedValue as Float
                    setTranslationXTop(value)
                }
                start()
            }
            currentTranslationX = -maxTranslationX
        }
    }

    //文字和按钮区域平移动画
    private fun shiftPage(isBack: Boolean) {
        Log.i("文字区域平移", "shiftPage isBack=$isBack currentPage=$currentPage")
        if (isBack) currentPage--
        Log.i("文字区域平移", "shiftPage isBack=$isBack currentPage=$currentPage")
        when (currentPage) {
            0 -> {
                if (isBack) {
                    animateLayoutTransition(
                        binding.conRegisterContentTwo,
                        binding.conRegisterContentOne,
                        binding.conRegisterBtnTwo,
                        binding.conRegisterBtnOne
                    )
                    binding.imgRegisterBack.visibility = View.GONE
                } else {
                    animateLayoutTransition(
                        binding.conRegisterContentOne,
                        binding.conRegisterContentTwo,
                        binding.conRegisterBtnOne,
                        binding.conRegisterBtnTwo
                    )
                    currentPage++
                    binding.imgRegisterBack.visibility = View.VISIBLE
                }
            }

            1 -> {
                if (isBack) {
                    animateLayoutTransition(
                        binding.conRegisterContentThree,
                        binding.conRegisterContentTwo,
                        binding.conRegisterBtnThree,
                        binding.conRegisterBtnTwo
                    )
                } else {
                    animateLayoutTransition(
                        binding.conRegisterContentTwo,
                        binding.conRegisterContentThree,
                        binding.conRegisterBtnTwo,
                        binding.conRegisterBtnThree
                    )
                    currentPage++
                    binding.imgRegisterBack.visibility = View.VISIBLE
                }
            }

            2 -> {
                animateLayoutTransition(
                    binding.conRegisterContentThree,
                    binding.conRegisterContentOne,
                    binding.conRegisterBtnThree,
                    binding.conRegisterBtnOne
                )
                currentPage = 0
                binding.imgRegisterBack.visibility = View.GONE
            }
        }
    }

    private fun animateLayoutTransition(
        hideLayout: ConstraintLayout, showLayout: ConstraintLayout,
        hideBtnLayout: ConstraintLayout,
        showBtnLayout: ConstraintLayout,
    ) {
        val screenWidth = resources.displayMetrics.widthPixels.toFloat()

        //文字区域
        hideLayout.animate()
            .translationX(-screenWidth)
            .setDuration(500)
            .withEndAction {
                hideLayout.visibility = View.GONE
                hideLayout.translationX = 0f
            }
        showLayout.translationX = screenWidth
        showLayout.visibility = View.VISIBLE
        showLayout.animate()
            .translationX(0f)
            .setDuration(500)

        //按钮
        hideBtnLayout.animate()
            .translationX(-screenWidth)
            .setDuration(500)
            .withEndAction {
                hideBtnLayout.visibility = View.GONE
                hideBtnLayout.translationX = 0f
            }
        showBtnLayout.translationX = screenWidth
        showBtnLayout.visibility = View.VISIBLE
        showBtnLayout.animate()
            .translationX(0f)
            .setDuration(500)
    }

    //点击物理返回按键
    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (currentPage > 0) {
            //不是第一页
            shiftImageTop(true)
            shiftImageMiddle(true)
            shiftImageBottom(true)
            shiftPage(true)
        } else {
            //是第一页
            super.onBackPressed()
        }
    }

    companion object {
        fun start(context: Context?) {
            context?.startActivity(Intent(context, RegisterActivity::class.java))
        }
    }
}
